<template>
  <el-row type="flex" justify="center" class="bg">
    <div class="reg">
      <h2 style="text-align:center;margin:0">登录</h2>
      <el-form
        ref="formData"
        :model="formData"
        :rules="rules"
        label-width="80px"
        @keyup.enter.native="login()"
        style="width:400px"
      >
        <el-form-item prop="email" label="邮箱">
          <el-input
            v-model="formData.email"
            placeholder="请输入邮箱"
            prefix-icon="icon-login_user"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input
            v-model="formData.password"
            placeholder="请输入密码"
            type="password"
            prefix-icon="icon-login_pwd"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="btn" @click="login('formData')" icon="el-icon-upload">登录</el-button>
          <el-button @click="resetForm('formData')">重置</el-button>
        </el-form-item>

        <router-link style="position:relative;left:100px;" to="register">没有密码？注册</router-link>
      </el-form>
    </div>
  </el-row>
</template>
<script>
export default {
  data() {
    return {
      formData: {},
      rules: {
        email: [
          { required: true, message: "邮箱不能为空", trigger: "blur" }
        ],
        password: [{ required: true, message: "密码不能为空", trigger: "blur" }]
      }
    };
  },
  methods: {
    login(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const res = await this.$http.post('/users/login', {...this.formData})
          this.$store.commit('SET_TOKEN', res.data.token)
          this.$store.commit('SET_NAME', res.data.name)
          this.$store.commit('SET_AVATAR', res.data.avatar)
          this.$store.commit('SET_LOGIN_STATE', true)
          this.$message({
            type: "success",
            message: "登录成功"
          });
          this.$router.push('/');
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>
<style lang="less" scoped>
@import "../assets/style/login";
</style>